//
//  ChatScreenViewController.m
//  Bluetooth Chat App
//
//  Created by iD Student on 7/17/13.
//  Copyright (c) 2013 ZTBWorks. All rights reserved.
//

#import "ChatScreenViewController.h"

@interface ChatScreenViewController ()

@end

@implementation ChatScreenViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    chatView.delegate = self;
    chatView.dataSource = self;
    textField.delegate = self;
    NSLog([@"Username: " stringByAppendingString:self.appDelegate.username]);
    self.appDelegate.currentSession.delegate = self;
    chatMessages = [[NSMutableArray alloc] init];

}

- (void) viewDidAppear:(BOOL)animated
{
    [chatView reloadData];
}

- (void) goToSettings:(id)sender
{
    SettingsViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SettingsView"];
    [self presentViewController:viewController animated:YES completion:nil];
}

-(AppDelegate *) appDelegate{
    
    return [UIApplication sharedApplication].delegate;
}

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.25 animations:^{
        chatView.center = CGPointMake(chatView.center.x, chatView.center.y - 210);
        textField.center = CGPointMake(textField.center.x, textField.center.y - 210);
    }];
}



- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    NSData* data;
    NSString *str = [[self.appDelegate.username stringByAppendingFormat:@": "] stringByAppendingString:textField.text];
    [chatMessages addObject:str];
    NSLog([@"Data Sent " stringByAppendingString:str]);
    data = [str dataUsingEncoding: NSASCIIStringEncoding];
    [self mySendDataToPeers:data];
    [UIView animateWithDuration:0.25 animations:^{
        chatView.center = CGPointMake(chatView.center.x, chatView.center.y + 210);
        textField.center = CGPointMake(textField.center.x, textField.center.y + 210);
    }];
    [chatView reloadData];
    textField.text = @"";
    return YES; 
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [chatMessages count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    cell.textLabel.text = [chatMessages objectAtIndex:indexPath.row];
    if ([[[[chatMessages objectAtIndex:indexPath.row] componentsSeparatedByString:@": "] objectAtIndex:0] isEqualToString:self.appDelegate.username]) {
        cell.textLabel.textAlignment = UITextAlignmentRight;
    }
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.font = self.appDelegate.selectedFont;
    return cell;
}
 

- (void) mySendDataToPeers:(NSData *) data
{
    if (self.appDelegate.currentSession)
    {
        [self.appDelegate.currentSession sendDataToAllPeers:data withDataMode:GKSendDataReliable
                                                                                                   error:nil];
    }
}

- (void) peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
    session.delegate = self;
    [session setDataReceiveHandler:self withContext:nil];
    picker.delegate = nil;
    
    [picker dismiss];
}

- (void) receiveData:(NSData *)data
            fromPeer:(NSString *)peer
           inSession:(GKSession *)session
             context:(void *)context {
    
    //---convert the NSData to NSString---
    NSLog(@"data recieved");
    NSString* str;
    str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    [chatMessages addObject:str];

    [chatView reloadData];
    
}

- (void) session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state{
    switch (state) {
        case GKPeerStateDisconnected:{
                [self dismissViewControllerAnimated:YES completion:^{
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Disconnected"
                                                                    message:@"You were disconnected because your partner(s) either disconnected or there was a problem connecting the their device(s)"
                                                                   delegate:self
                                                          cancelButtonTitle:@"OK"
                                                          otherButtonTitles:nil];
                [alertView show];
                }];}
            break;
            
        default:
            break;
    }
}


- (void)viewDidUnload {
    [super viewDidUnload];
}


@end
